package com.sdkj.recruit.util;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.List;
import java.util.Map;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.TopLevelWindow;
import com.gargoylesoftware.htmlunit.UnexpectedPage;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.WebResponseData;
import com.gargoylesoftware.htmlunit.WebWindow;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.DomNodeList;
import com.gargoylesoftware.htmlunit.html.HtmlDivision;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlListItem;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSpan;
import com.gargoylesoftware.htmlunit.html.HtmlTableRow;
import com.gargoylesoftware.htmlunit.javascript.host.html.HTMLAnchorElement;
import com.gargoylesoftware.htmlunit.util.WebConnectionWrapper;

/**
 * 
 * @author 黄宝康 模拟点击超链接演示
 */
public class HtmlUnitTest {
    public static void main(String[] args) {
    	
    	
		//String result = HttpAccessUtil.httpGet("http://pis.baiwang.com/bwmg/mix/bw/getPdfUrl?invoiceId=1700372004352");

		
    	/*WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52); // 实例化Web客户端

    	 try {
    		UnexpectedPage page = webClient.getPage("http://pis.baiwang.com/bwmg/mix/bw/getPdfUrl?invoiceId=1700372004352");
		  byte [] bytes = new byte[page.getInputStream().available()];
		  page.getInputStream().read(bytes);
			String str = new String(bytes);
			System.out.println(str);
			webClient.close();
		} catch (FailingHttpStatusCodeException | IOException e) {
			e.printStackTrace();
		}*/
    	
    	//jar();
        baiwang();
    	//ruihong();
    }
    
    private static void jar() {
		// TODO Auto-generated method stub
    	WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52); // 实例化Web客户端
        try {
        	
        	// 取消 JS 支持
            webClient.getOptions().setJavaScriptEnabled(false);
            // 取消 CSS 支持
            webClient.getOptions().setCssEnabled(false);
            
            HtmlPage page = webClient.getPage("https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-catalina/9.0.12");
            
            DomElement element = page.getElementById("maincontent");// 获取ul元素
            HtmlTableRow item = (HtmlTableRow) element.getByXPath("//table//tbody//tr").get(4);// 获取ul元素下的第三个li标签
            HtmlElement a = item.getElementsByTagName("a").get(0);// 得到产品中心的超链接元素
            UnexpectedPage result_page = a.click();// 模拟点击
            FileOutputStream out =new FileOutputStream(new File("d:\\1.jar"));
            out.write(toByteArray(result_page.getInputStream()));
            //System.out.println(result_page.getInputStream());
            out.close();
        } catch (FailingHttpStatusCodeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            webClient.close(); // 关闭客户端，释放内存
        }
	}

	/**
     * 瑞宏发票下载
     */
    private static void ruihong() {
    	try {
			// TODO Auto-generated method stub
			WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52); // 实例化Web客户端
			// 取消 JS 支持
			webClient.getOptions().setJavaScriptEnabled(false);
			// 取消 CSS 支持
			webClient.getOptions().setCssEnabled(false);
			
			HtmlPage page = webClient.getPage("https://www.chinaeinv.com/p.jspa?c=2B2AB5A9BEC8DA6ED366");
			
			DomElement dom = null;
            		
    		DomNodeList<DomElement> elementsByTagNameSubmit = page.getElementsByTagName("span");
    		
    		List<Object> obj =elementsByTagNameSubmit.get(0).getByXPath("//div//div//div//span");
    		
    		
            for (DomElement domElement : elementsByTagNameSubmit) {
                // 根据目标元素 class 属性循环匹配
                if (domElement.getAttribute("class").equals("container-fluid")) {
                	dom =domElement; // 转类型只是为了下面能模拟点击，转或者不转视情况而定
                    break;
                }
            }
            HtmlElement submit = null;
            if(dom !=null) {
            	List<HtmlSpan> submit1 = dom.getByXPath("//div");
            	
            	for (HtmlSpan domElement : submit1) {
                    // 根据目标元素 class 属性循环匹配
                    if (domElement.getAttribute("class").equals("pull-right")) {
                    	submit = (HtmlElement) domElement; // 转类型只是为了下面能模拟点击，转或者不转视情况而定
                        break;
                    }
                }
            	System.out.println("ds");
            	/*for (DomElement domElement : submit1) {
                    // 根据目标元素 class 属性循环匹配
                    if (domElement.getAttribute("class").equals("btn btn-info inv-pdf")) {
                    	submit = (HtmlElement) domElement; // 转类型只是为了下面能模拟点击，转或者不转视情况而定
                        break;
                    }
                }*/
            }
            
            submit.click();

            webClient.close();
			
		} catch (FailingHttpStatusCodeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
    	
	}

    static String url ="";
	private static void baiwang() {
		// TODO Auto-generated method stub
    	WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52); // 实例化Web客户端
        try {
        	
        	// 开启JS 支持
            webClient.getOptions().setJavaScriptEnabled(true);
            // 取开启CSS 支持
            webClient.getOptions().setCssEnabled(true);
            // 支持ajax
            webClient.setAjaxController(new NicelyResynchronizingAjaxController());
            webClient.getOptions().setRedirectEnabled(true);
			webClient.setWebConnection(new WebConnectionWrapper(webClient) {
				public WebResponse getResponse(WebRequest request) throws IOException {
					WebResponse response = super.getResponse(request);
					if (request.getUrl().toExternalForm().contains("getPdfUrl")) {

						Map<String, String> map = request.getAdditionalHeaders();

						String result =map.get("Referer");

						url = request.getUrl().toString();

						// String result =HttpAccessUtil.httpGetSSL(url);
						System.out.println("################----" + url);
						String content = response.getContentAsString();
						WebResponseData data = new WebResponseData(content.getBytes("UTF-8"), response.getStatusCode(),
								response.getStatusMessage(), response.getResponseHeaders());
						response = new WebResponse(data, request, response.getLoadTime());
					}
					
					url = response.getWebRequest().getUrl().toString();
					System.out.println("result ################----" + url);
					
					return response;
				}
			}

			);
            
            HtmlPage page = webClient.getPage("http://pis.baiwang.com/title/saomakaipiao/previewInvoice.html?param=8F5AC428D13F9B8FFF312591874342F1C98AE3397531811E3647EE376361CE09#");
            DomElement element = page.getElementById("bigZoom");// 获取ul元素
            HtmlDivision item = (HtmlDivision) element.getByXPath("//div//div").get(0);// 获取ul元素下的第三个li标签
            HtmlElement a = item.getElementsByTagName("a").get(0);// 得到产品中心的超链接元素
            
            
            HtmlPage result_page = a.click();// 模拟点击
            //test
            
            WebResponse res = result_page.getWebResponse();	
            System.out.println("#############,"+res.getWebRequest().getUrl());
            
            
            String html = res.getContentAsString();	
            //System.out.println(html);
            
            /*FileOutputStream out =new FileOutputStream(new File("d:\\1.jar"));
            out.write(toByteArray(result_page.getInputStream()));
            //System.out.println(result_page.getInputStream());
            out.close();*/
            
            FileOutputStream out =new FileOutputStream(new File("d:\\1.pdf"));
            out.write(toByteArray(res.getContentAsStream()));
            out.close();
        } catch (FailingHttpStatusCodeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            webClient.close(); // 关闭客户端，释放内存
        }
	}

	
	public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }
}
